<template>
  <div>
    <!--  面包屑-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--    卡片-->
    <el-card>
      <!--   添加按钮区域   -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 表格-->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template #default="scope">
            <el-row :class="['bdBottom',i1 === 0 ? 'bdTop' : '','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row :class="[i2 === 0 ? '' : 'bdTop','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                        <el-tag closable @close="removeRightById(scope.row, item3.id)" v-for="item3 in item2.children" :key="item3.id" type="warning">{{item3.authName}}</el-tag>
                  </el-col>
                 </el-row>
              </el-col>
            </el-row>
<!--            {{scope.row}}-->
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
<!--            {{scope.row}}-->
            <el-button type="primary" icon="el-icon-edit" size="small" @click="editDialog(scope.row)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteRole(scope.row.id)">删除</el-button>
            <el-button type="warning" icon="el-icon-s-tools" size="small" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--  添加角色的对话框  -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialogVisible" width="50%" @close="resetAddRoleForm">
      <el-form :model="addRoleForm" :rules="addRoleFormRules" ref="addRoleFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleForm">确 定</el-button>
      </span>
    </el-dialog>
    <!--  编辑角色的对话框  -->
    <el-dialog title="编辑" :visible.sync="editRoleDialogVisible" width="50%" @close="resetEditDialog">
      <el-form :model="editRoleForm" :rules="editRoleFormRules" ref="editRoleFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditData">确 定</el-button>
      </span>
    </el-dialog>
<!--    分配权限的对话框-->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="35%" @close="clearDefKeys">
      <el-tree :data="rightList" :props="treeProps" ref="treeRef"
               show-checkbox node-key="id" default-expand-all
               :default-checked-keys="defKeys"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
       <el-button type="primary" @click="setRoleRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data () {
    return {
      rolesList: [],
      addRoleDialogVisible: false,
      addRoleForm: {},
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      editRoleDialogVisible: false,
      editRoleForm: {},
      editRoleFormRules: {},
      // 选中编辑的ID
      selectByID: 0,
      setRightsDialogVisible: false,
      // 所有权限列表
      rightList: [],
      // 树的控件
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 分配权限里的，当前角色的所有的权限
      defKeys: [],
      // 当前用户的 ID 值
      roleID: 0
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取角色列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.rolesList = res.data
      // console.log(this.rolesList)
    },
    // 重置添加用户表单
    resetAddRoleForm () {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 添加角色
    saveRoleForm () {
      this.$refs.addRoleFormRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        // console.log(res)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.addRoleDialogVisible = false
        this.getRolesList()
        this.$message.success('添加成功')
      })
    },
    // 点击编辑按钮 将数据传到 edit 表单里
    editDialog (row) {
      this.selectByID = row.id
      console.log(this.selectByID)
      this.editRoleDialogVisible = true
      this.editRoleForm = { ...row }
      // console.log(this.editRoleForm)
    },
    async saveEditData () {
      const { data: res } = await this.$http.put('roles/' + this.selectByID, this.editRoleForm)
      if (res.meta.status !== 200) return this.$message.error('保存数据失败')
      console.log(res)
      this.getRolesList()
      this.editRoleDialogVisible = false
      this.$message.success('修改成功')
    },
    // 重置编辑表单
    resetEditDialog () {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 删除角色
    deleteRole (id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该角色, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + id)
        // console.log(res)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.getRolesList()
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 删除角色权限
    async removeRightById (role, rightId) {
      const comfirmResult = await this.$confirm('此操作将永久该权限, 是否继续?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (comfirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete('roles/' + role.id + '/rights/' + rightId)
      if (res.meta.status !== 200) {
        return this.$message.error('权限删除失败')
      }
      role.children = res.data
      this.$message.success('权限删除成功')
    },
    // 展示分配权限的对话框，还有取到该用户所拥有的的权限
    async showSetRightsDialog (role) {
      this.roleID = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error('获取全部权限失败')
      this.rightList = res.data
      console.log(this.rightList)
      this.getLeftKeys(role, this.defKeys)
      this.setRightsDialogVisible = true
    },
    // 递归去调用当前角色的三级子节点
    getLeftKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeftKeys(item, arr)
      })
    },
    // 每次关闭分配权限对话框时，清空 defKeys 的数值
    clearDefKeys () {
      this.defKeys = []
    },
    async setRoleRights () {
      const checkedRight = [...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()]
      const strID = checkedRight.join(',')
      // console.log(strID)
      const { data: res } = await this.$http.post('roles/' + this.roleID + '/rights', { rids: strID })
      if (res.meta.status !== 200) return this.$message.error('权限更新失败')
      this.getRolesList()
      this.$message.success('更新成功')
      this.setRightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdBottom{
  border-bottom: 1px solid #ccc;
}
.bdTop{
  border-top: 1px solid #ccc;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
